import { useCallback, useRef, useState } from 'react';

export interface LongPressConfig {
  delay: number; // 长按触发延迟 (毫秒)
  threshold: number; // 移动阈值 (像素)
}

export interface LongPressState {
  isLongPressing: boolean;
  startTime: number;
  startPosition: { x: number; y: number };
  currentPosition: { x: number; y: number };
}

export const useLongPressDrag = (config: LongPressConfig = { delay: 500, threshold: 5 }) => {
  const [longPressState, setLongPressState] = useState<LongPressState>({
    isLongPressing: false,
    startTime: 0,
    startPosition: { x: 0, y: 0 },
    currentPosition: { x: 0, y: 0 },
  });

  const longPressTimerRef = useRef<NodeJS.Timeout | null>(null);
  const onLongPressStartRef = useRef<(() => void) | null>(null);
  const onLongPressEndRef = useRef<(() => void) | null>(null);

  // 清除计时器
  const clearLongPressTimer = useCallback(() => {
    if (longPressTimerRef.current) {
      clearTimeout(longPressTimerRef.current);
      longPressTimerRef.current = null;
    }
  }, []);

  // 开始长按检测
  const startLongPress = useCallback((
    event: React.MouseEvent | MouseEvent,
    onLongPressStart?: () => void,
    onLongPressEnd?: () => void
  ) => {
    event.preventDefault();
    
    const startX = event.clientX;
    const startY = event.clientY;
    const startTime = Date.now();

    // 更新回调引用
    onLongPressStartRef.current = onLongPressStart || null;
    onLongPressEndRef.current = onLongPressEnd || null;

    setLongPressState({
      isLongPressing: false,
      startTime,
      startPosition: { x: startX, y: startY },
      currentPosition: { x: startX, y: startY },
    });

    // 设置长按计时器
    longPressTimerRef.current = setTimeout(() => {
      console.log('🔥 长按触发 - 开始批量拖拽');
      
      setLongPressState(prev => ({
        ...prev,
        isLongPressing: true,
      }));

      // 触发长按开始回调
      if (onLongPressStartRef.current) {
        console.log('🎯 执行长按开始回调');
        onLongPressStartRef.current();
      } else {
        console.warn('❌ 长按开始回调未定义');
      }
    }, config.delay);

    // 添加全局鼠标事件监听
    const handleMouseMove = (moveEvent: MouseEvent) => {
      const deltaX = Math.abs(moveEvent.clientX - startX);
      const deltaY = Math.abs(moveEvent.clientY - startY);
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

      // 更新当前位置
      setLongPressState(prev => ({
        ...prev,
        currentPosition: { x: moveEvent.clientX, y: moveEvent.clientY },
      }));

      // 如果移动距离超过阈值，取消长按
      if (distance > config.threshold && !longPressState.isLongPressing) {
        console.log('❌ 移动距离超过阈值，取消长按');
        clearLongPressTimer();
      }
    };

    const handleMouseUp = () => {
      console.log('🔚 鼠标释放 - 结束长按检测');
      
      // 清除计时器
      clearLongPressTimer();

      // 如果正在长按，触发结束回调
      if (longPressState.isLongPressing && onLongPressEndRef.current) {
        onLongPressEndRef.current();
      }

      // 重置状态
      setLongPressState({
        isLongPressing: false,
        startTime: 0,
        startPosition: { x: 0, y: 0 },
        currentPosition: { x: 0, y: 0 },
      });

      // 移除全局事件监听
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    // 添加全局事件监听
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  }, [config.delay, config.threshold, clearLongPressTimer, longPressState.isLongPressing]);

  // 取消长按
  const cancelLongPress = useCallback(() => {
    console.log('🚫 手动取消长按');
    clearLongPressTimer();
    setLongPressState({
      isLongPressing: false,
      startTime: 0,
      startPosition: { x: 0, y: 0 },
      currentPosition: { x: 0, y: 0 },
    });
  }, [clearLongPressTimer]);

  // 检查是否可以开始长按
  const canStartLongPress = useCallback(() => {
    return !longPressState.isLongPressing && longPressTimerRef.current === null;
  }, [longPressState.isLongPressing]);

  // 获取长按进度 (0-1)
  const getLongPressProgress = useCallback(() => {
    if (longPressState.isLongPressing) return 1;
    if (longPressState.startTime === 0) return 0;
    
    const elapsed = Date.now() - longPressState.startTime;
    return Math.min(elapsed / config.delay, 1);
  }, [longPressState.startTime, longPressState.isLongPressing, config.delay]);

  return {
    longPressState,
    startLongPress,
    cancelLongPress,
    canStartLongPress,
    getLongPressProgress,
  };
};

export default useLongPressDrag;
